package com.zhende.hr.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import com.zhende.hr.interceptor.JWTFilter;
import com.zhende.hr.service.impl.CustomUserDetailsService;
import com.zhende.hr.utils.JwtTokenProvider;

//@Configuration
//@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private JWTFilter jwtFilter;

    @Autowired
    private JwtTokenProvider jwtTokenProvider;

    @Autowired
    private CustomUserDetailsService userDetailsService;
    @Autowired
    private CustomAccessDeniedHandler customAccessDeniedHandler;
    
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf().disable()  // 禁用 CSRF 防护
            .authorizeRequests()
                .antMatchers("/u/login").permitAll()  // 登录接口无需认证
                .antMatchers("/xxx").permitAll()  // 登录接口无需认证
                .anyRequest().authenticated()  // 其他请求需要认证
                .and()
                .exceptionHandling()
                    .accessDeniedHandler(customAccessDeniedHandler) 
  
            .and().addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class);  // 在认证过滤器之前添加 JWTFilter
        
     // 打印一下日志，确保 SecurityConfig 正常加载
        System.out.println("SecurityConfig 配置加载完成");	
    }
    


    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService)  // 设置自定义的 UserDetailsService
            .passwordEncoder(passwordEncoder());  // 使用 BCrypt 加密
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();  // 使用 BCrypt 加密
        
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
}